package com.neu.cpsp.controller;
/*
    @author neu.xiangwenjuan
    @create 2022/3/26
*/

import com.auth0.jwt.interfaces.DecodedJWT;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.neu.cpsp.dao.EvaluateRecordToEmployeeMapper;
import com.neu.cpsp.pojo.*;
import com.neu.cpsp.service.EmployeeService;
import com.neu.cpsp.service.EvaluateRecordService;
import com.neu.cpsp.service.PerformanceHistoryService;
import com.neu.cpsp.util.JWTUtils;
import com.neu.cpsp.util.MD5Util;
import com.neu.cpsp.util.result.Result;
import com.neu.cpsp.util.result.ResultGenerator;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/data")
public class PerformanceHistoryController {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private PerformanceHistoryService performanceHistoryService;

    @Autowired
    private EvaluateRecordToEmployeeMapper evaluateRecordToEmployeeMapper;

    @Autowired
    private EvaluateRecordService evaluateRecordService;

    private EmployeeController employeeController = new EmployeeController();

    private MD5Util md5Util = new MD5Util();

    @ApiOperation("获得员工当前季度的绩效数据")
    @RequestMapping(value = "/getPerformanceInfo", method = RequestMethod.GET)
    @ResponseBody
    private Result getPerformanceInfo(@RequestParam(defaultValue = "1")Integer pageNum,
                                      @RequestParam(defaultValue = "10")Integer pageSize,
                                      HttpServletRequest request) {

        // 得到当前日期，从而获得年份和季度。
        Calendar calendar = Calendar.getInstance();
        Integer year = calendar.get(Calendar.YEAR);
        int quarter = employeeController.getSeason(new Date());

        // 根据年份和季度数，得到当前季度的初始绩效和上一季度的结束绩效。
        List<PerformanceHistory> currentPerformance = performanceHistoryService.selectPerformanceValue(year, quarter);
        List<PerformanceHistory> performanceHistories = new ArrayList<>();
        if (quarter > 1) {
            performanceHistories = performanceHistoryService.selectPerformanceValue(year, quarter - 1);
        }else {
            performanceHistories = performanceHistoryService.selectPerformanceValue(year - 1,4);
        }

        // 得到在当前季度每个员工因为违规所扣除的绩效比例的总和。
        List<EvaluateRecordCurrentQuarter> sumProp = evaluateRecordService.getSumProp(year,quarter);

        // 根据token得到用户信息。
        String token = request.getHeader("token");
        DecodedJWT verify = JWTUtils.verify(token);
        // 得到用户的工号，确认部门，根据角色判断用户权限。
        String role = verify.getClaim("role").asString();
        String jobNumber = verify.getClaim("jobNumber").asString();
        EmployeeEntity employeeRole = employeeService.selectByJobNumber(jobNumber);

        PageInfo<EmployeeEntity> source = new PageInfo<>();
        // 得到该角色能查看的员工数据
        List<EmployeeEntity> employees = new ArrayList<>();
        if (role.equals("admin") || role.equals("leader") || role.equals("supervision")) {
            source = PageHelper.startPage(pageNum, pageSize).doSelectPageInfo(() -> {
                employeeService.selectAll();
            });
            employees = new ArrayList<>(source.getList());
        }else if (role.equals("department")){
            source = PageHelper.startPage(pageNum, pageSize).doSelectPageInfo(() -> {
                employeeService.selectEmployeesByDepartment(employeeRole.getDepartment().getDepartmentId());
            });
            employees = new ArrayList<>(source.getList());
        }
        PageInfo<PerformanceInfo> target = new PageInfo<>();
        BeanUtils.copyProperties(source, target);

        List<PerformanceInfo> list = new ArrayList<>();

        DecimalFormat df = new DecimalFormat("######0.00");

        for (EmployeeEntity employee:employees) {
            PerformanceInfo performanceInfo = new PerformanceInfo();
            performanceInfo.setDepartment(employee.getDepartment().getDepartmentName());
            performanceInfo.setJobNumber(employee.getJobNumber());
            if (employee.getTeamGroup() != null) {
                performanceInfo.setTeamGroup(employee.getTeamGroup().getTeamGroupName());
            }else {
                performanceInfo.setTeamGroup("");
            }
            performanceInfo.setName(employee.getName());
            performanceInfo.setPosition(employee.getPositionType());
            for (PerformanceHistory current:currentPerformance) {
                if (employee.getIdCard().equals(current.getEmployeeIdCard())) {
                    for (EvaluateRecordCurrentQuarter sum:sumProp) {
                        if (sum.getEmployeeIdCard().equals(employee.getIdCard())) {
                            if (sum.getSumProp() >= 1) {
                                performanceInfo.setCurrentProp(0.0);
                                performanceInfo.setProp(1);
                            }else {
                                performanceInfo.setCurrentProp(Double.valueOf(df.format(current.getPerformanceValue()*(1 - sum.getSumProp()))));
                                performanceInfo.setProp(sum.getSumProp());
                            }
                            break;
                        }
                    }
                }
            }
            for (PerformanceHistory history:performanceHistories) {
                if (employee.getIdCard().equals(history.getEmployeeIdCard())) {
                    performanceInfo.setCurrentMoney(history.getPerformanceValue());
                }
            }
            list.add(performanceInfo);
        }
        // 对绩效按照currentProp进行排序。
        target.setList(list);
        return ResultGenerator.genSuccessResult(target);
    }

    @ApiOperation("获得员工当前季度的绩效数据")
    @RequestMapping(value = "/getPerformanceInfoSort", method = RequestMethod.GET)
    @ResponseBody
    private Result getPerformanceInfoSort() {
        // 得到当前日期，从而获得年份和季度。
        Calendar calendar = Calendar.getInstance();
        Integer year = calendar.get(Calendar.YEAR);
        int quarter = employeeController.getSeason(new Date());

        // 根据年份和季度数，得到当前季度的初始绩效和上一季度的结束绩效。
        List<PerformanceHistory> currentPerformance = performanceHistoryService.selectPerformanceValue(year, quarter);
        List<PerformanceHistory> performanceHistories = new ArrayList<>();
        if (quarter > 1) {
            performanceHistories = performanceHistoryService.selectPerformanceValue(year, quarter - 1);
        }else {
            performanceHistories = performanceHistoryService.selectPerformanceValue(year - 1,4);
        }

        // 得到在当前季度每个员工因为违规所扣除的绩效比例的总和。
        List<EvaluateRecordCurrentQuarter> sumProp = evaluateRecordService.getSumProp(year,quarter);
        List<EmployeeEntity> employees = new ArrayList<>();
        employees = employeeService.selectAll();
        List<PerformanceInfo> list = new ArrayList<>();

        DecimalFormat df = new DecimalFormat("######0.00");

        for (EmployeeEntity employee:employees) {
            PerformanceInfo performanceInfo = new PerformanceInfo();
            performanceInfo.setDepartment(employee.getDepartment().getDepartmentName());
            performanceInfo.setJobNumber(employee.getJobNumber());
            if (employee.getTeamGroup() != null) {
                performanceInfo.setTeamGroup(employee.getTeamGroup().getTeamGroupName());
            }else {
                performanceInfo.setTeamGroup("");
            }
            performanceInfo.setName(employee.getName());
            performanceInfo.setPosition(employee.getPositionType());
            for (PerformanceHistory current:currentPerformance) {
                if (employee.getIdCard().equals(current.getEmployeeIdCard())) {
                    for (EvaluateRecordCurrentQuarter sum:sumProp) {
                        if (sum.getEmployeeIdCard().equals(employee.getIdCard())) {
                            if (sum.getSumProp() >= 1) {
                                performanceInfo.setCurrentProp(0.0);
                                performanceInfo.setProp(1);
                            }else {
                                performanceInfo.setCurrentProp(Double.valueOf(df.format(current.getPerformanceValue()*(1 - sum.getSumProp()))));
                                performanceInfo.setProp(1-sum.getSumProp());
                            }
                            break;
                        }
                    }
                }
            }
            for (PerformanceHistory history:performanceHistories) {
                if (employee.getIdCard().equals(history.getEmployeeIdCard())) {
                    performanceInfo.setCurrentMoney(history.getPerformanceValue());
                }
            }
            list.add(performanceInfo);
        }
        // 对绩效按照currentProp进行排序。
        List<PerformanceInfo> result = new ArrayList<>();
        result = sortList(list, list.size());
        return ResultGenerator.genSuccessResult(result);
    }

    /**
     * 工具类：排序类，对绩效信息进行排序。
     */
    private List<PerformanceInfo> sortList(List<PerformanceInfo> list, int size) {
        for (int i = 0;i < size - 1; i ++) {
            for (int j = 0; j < size - i - 1; j ++) {
                if (list.get(j).getCurrentProp() < list.get(j + 1).getCurrentProp()) {
                    double temp = 0;
                    temp = list.get(j + 1).getCurrentProp();
                    list.get(j + 1).setCurrentProp(list.get(j).getCurrentProp());
                    list.get(j).setCurrentProp(temp);
                }
            }
        }
        return list;
    }


    @Scheduled(cron = " 0 00 00 1 4,7,10,1 ?")
    private void updatePerformanceQuarter() {
        // 每个季度结束时，需要更新下一季度绩效的初值，其中生产岗累加100，辅助岗累加50。
        // 得到当前年份和季度。
        Calendar calendar = Calendar.getInstance();
        Integer year = calendar.get(Calendar.YEAR);
        int quarter = employeeController.getSeason(new Date());
        // 上季度的绩效的初始值。
        List<PerformanceHistory> histories = new ArrayList<>();
        List<EvaluateRecordCurrentQuarter> sumProp = new ArrayList<>();
        if (quarter > 1) {
            histories = performanceHistoryService.selectPerformanceValue(year, quarter - 1);
            sumProp = evaluateRecordService.getSumProp(year,quarter - 1);
        }else {
            histories = performanceHistoryService.selectPerformanceValue(year - 1,4);
            sumProp = evaluateRecordService.getSumProp(year - 1,4);
        }
        // 先计算上季度绩效的实际值。
        for (EvaluateRecordCurrentQuarter sum : sumProp) {
            for (PerformanceHistory history:histories) {
                if (sum.getEmployeeIdCard().equals(history.getEmployeeIdCard())) {
                    if (sum.getSumProp() > 1)
                        history.setPerformanceValue(0.0);
                    history.setPerformanceValue(history.getPerformanceValue() * (1 - sum.getSumProp()));
                }
            }
        }
        // 不得更新上一季度的历史绩效信息嘛。
        for (PerformanceHistory history :histories) {
            performanceHistoryService.updateByPrimaryKeySelective(history);
        }
        // 需要先更新本季度的绩效值。
        for (PerformanceHistory history : histories) {
            if (employeeService.getIsDirectProducer(history.getEmployeeIdCard())) {
                if (history.getPerformanceValue() <= 900)
                    history.setPerformanceValue(history.getPerformanceValue() + 100);
                history.setPerformanceValue(1000.0);
            }else {
                if (history.getPerformanceValue() <= 450)
                    history.setPerformanceValue(history.getPerformanceValue() + 50);
                history.setPerformanceValue(500.0);
            }
            history.setYear(year);
            history.setQuarter(quarter);
            performanceHistoryService.insert(history);
        }
    }
}
